package com.zhong.demo.fragment;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

import com.zhong.demo.fragment.fragment.AFragment;
import com.zhong.demo.fragment.fragment.BFragment;
import com.zhong.demo.fragment.fragment.CFragment;
import com.zhong.demo.fragment.fragment.FragmentAdapter;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private TabLayout tabLayout;

    private ViewPager viewPager;
    private FragmentPagerAdapter adapter;
    private List<Fragment> fragmentList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initData();
        initViewPager();
        initTabLayout();
    }

    private void initView() {
        tabLayout = findViewById(R.id.tab_layout);
        viewPager = findViewById(R.id.man_view_pager);
    }

    private void initTabLayout(){
        for(int i = 0; i < fragmentList.size(); i++){
            TabLayout.Tab tab = tabLayout.newTab().setText("Fragment" + i);
            tabLayout.addTab(tab);
        }

        tabLayout.setupWithViewPager(viewPager);
    }

    private void initViewPager(){
        if(adapter == null){
            adapter = new FragmentAdapter(getSupportFragmentManager(),fragmentList);
            viewPager.setAdapter(adapter);
        }
    }

    private void initData(){
        fragmentList = new ArrayList<>();
        fragmentList.add(new AFragment());
        fragmentList.add(new BFragment());
        fragmentList.add(new CFragment());
    }
}
